import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  useColorScheme,
  Switch,
  Alert,
  TextInput,
} from 'react-native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { RootStackParamList } from '../types';

type TimerSettingsScreenProps = NativeStackScreenProps<RootStackParamList, 'TimerSettings'>;

interface TimerPreset {
  id: string;
  name: string;
  minutes: number;
  seconds: number;
  isDefault: boolean;
}

const TimerSettingsScreen: React.FC<TimerSettingsScreenProps> = ({ navigation }) => {
  const isDarkMode = useColorScheme() === 'dark';
  
  // 定时器预设
  const [presets, setPresets] = useState<TimerPreset[]>([
    { id: '1', name: '泡面', minutes: 3, seconds: 0, isDefault: true },
    { id: '2', name: '面膜', minutes: 15, seconds: 0, isDefault: true },
    { id: '3', name: '短休息', minutes: 5, seconds: 0, isDefault: false },
    { id: '4', name: '冥想', minutes: 10, seconds: 0, isDefault: false },
  ]);
  
  // 新预设表单
  const [newPresetName, setNewPresetName] = useState('');
  const [newPresetMinutes, setNewPresetMinutes] = useState('');
  const [newPresetSeconds, setNewPresetSeconds] = useState('');
  const [showAddForm, setShowAddForm] = useState(false);
  
  // 添加新预设
  const addNewPreset = () => {
    if (!newPresetName) {
      Alert.alert('错误', '请输入预设名称');
      return;
    }
    
    if (!newPresetMinutes && !newPresetSeconds) {
      Alert.alert('错误', '请输入时间');
      return;
    }
    
    const minutes = parseInt(newPresetMinutes) || 0;
    const seconds = parseInt(newPresetSeconds) || 0;
    
    if (minutes === 0 && seconds === 0) {
      Alert.alert('错误', '时间不能为0');
      return;
    }
    
    const newPreset: TimerPreset = {
      id: Date.now().toString(),
      name: newPresetName,
      minutes,
      seconds,
      isDefault: false,
    };
    
    setPresets([...presets, newPreset]);
    setNewPresetName('');
    setNewPresetMinutes('');
    setNewPresetSeconds('');
    setShowAddForm(false);
    
    Alert.alert('成功', `已添加"${newPresetName}"预设`);
  };
  
  // 删除预设
  const deletePreset = (id: string) => {
    const presetToDelete = presets.find(p => p.id === id);
    
    if (presetToDelete?.isDefault) {
      Alert.alert('错误', '默认预设不能删除');
      return;
    }
    
    Alert.alert(
      '删除预设',
      '确定要删除这个预设吗？',
      [
        { text: '取消', style: 'cancel' },
        { 
          text: '确定', 
          onPress: () => {
            const updatedPresets = presets.filter(p => p.id !== id);
            setPresets(updatedPresets);
            Alert.alert('成功', '预设已删除');
          }
        }
      ]
    );
  };
  
  // 使用预设
  const usePreset = (preset: TimerPreset) => {
    navigation.navigate('PomodoroTimer', { 
      initialMinutes: preset.minutes,
      initialSeconds: preset.seconds,
      presetName: preset.name
    } as any);
  };
  
  return (
    <ScrollView 
      style={[styles.container, isDarkMode && styles.darkContainer]}
      showsVerticalScrollIndicator={false}
    >
      <Text style={[styles.title, isDarkMode && styles.lightText]}>
        定时器设置
      </Text>
      
      <View style={styles.presetsContainer}>
        <View style={styles.sectionHeader}>
          <Text style={[styles.sectionTitle, isDarkMode && styles.lightText]}>
            常用预设
          </Text>
          <TouchableOpacity 
            style={styles.addButton}
            onPress={() => setShowAddForm(!showAddForm)}
          >
            <Text style={styles.addButtonText}>
              {showAddForm ? '取消' : '+ 添加'}
            </Text>
          </TouchableOpacity>
        </View>
        
        {showAddForm && (
          <View style={styles.addFormContainer}>
            <TextInput
              style={styles.input}
              placeholder="预设名称"
              value={newPresetName}
              onChangeText={setNewPresetName}
            />
            <View style={styles.timeInputContainer}>
              <TextInput
                style={[styles.input, styles.timeInput]}
                placeholder="分钟"
                keyboardType="numeric"
                value={newPresetMinutes}
                onChangeText={setNewPresetMinutes}
              />
              <Text style={styles.timeInputLabel}>分</Text>
              <TextInput
                style={[styles.input, styles.timeInput]}
                placeholder="秒钟"
                keyboardType="numeric"
                value={newPresetSeconds}
                onChangeText={setNewPresetSeconds}
              />
              <Text style={styles.timeInputLabel}>秒</Text>
            </View>
            <TouchableOpacity 
              style={styles.saveButton}
              onPress={addNewPreset}
            >
              <Text style={styles.saveButtonText}>保存</Text>
            </TouchableOpacity>
          </View>
        )}
        
        {presets.map((preset) => (
          <View key={preset.id} style={styles.presetItem}>
            <View style={styles.presetInfo}>
              <Text style={[styles.presetName, isDarkMode && styles.lightText]}>
                {preset.name}
                {preset.isDefault && <Text style={styles.defaultTag}> (默认)</Text>}
              </Text>
              <Text style={styles.presetTime}>
                {preset.minutes > 0 && `${preset.minutes}分`}
                {preset.seconds > 0 && `${preset.seconds}秒`}
              </Text>
            </View>
            <View style={styles.presetActions}>
              <TouchableOpacity 
                style={[styles.actionButton, styles.useButton]}
                onPress={() => usePreset(preset)}
              >
                <Text style={styles.useButtonText}>使用</Text>
              </TouchableOpacity>
              {!preset.isDefault && (
                <TouchableOpacity 
                  style={[styles.actionButton, styles.deleteButton]}
                  onPress={() => deletePreset(preset.id)}
                >
                  <Text style={styles.deleteButtonText}>删除</Text>
                </TouchableOpacity>
              )}
            </View>
          </View>
        ))}
      </View>
      
      <View style={styles.tipsContainer}>
        <Text style={styles.tipsTitle}>使用提示</Text>
        <Text style={styles.tipsText}>
          • 点击"使用"按钮可直接启动对应的定时器{'\n'}
          • 默认预设不能删除{'\n'}
          • 您可以添加自定义预设，方便快速使用
        </Text>
      </View>
      
      {/* 底部空间 */}
      <View style={{height: 40}} />
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    backgroundColor: '#f5f5f5',
  },
  darkContainer: {
    backgroundColor: '#121212',
  },
  lightText: {
    color: '#fff',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    color: '#333',
  },
  presetsContainer: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 16,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  addButton: {
    paddingVertical: 6,
    paddingHorizontal: 12,
    backgroundColor: '#f0f0f0',
    borderRadius: 16,
  },
  addButtonText: {
    color: '#2196F3',
    fontWeight: '500',
  },
  addFormContainer: {
    backgroundColor: '#f9f9f9',
    padding: 16,
    borderRadius: 8,
    marginBottom: 16,
  },
  input: {
    backgroundColor: '#fff',
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    padding: 10,
    marginBottom: 12,
  },
  timeInputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  timeInput: {
    flex: 1,
    marginBottom: 0,
    marginRight: 8,
  },
  timeInputLabel: {
    fontSize: 16,
    color: '#666',
    marginRight: 16,
  },
  saveButton: {
    backgroundColor: '#2196F3',
    borderRadius: 8,
    padding: 12,
    alignItems: 'center',
  },
  saveButtonText: {
    color: '#fff',
    fontWeight: 'bold',
  },
  presetItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  presetInfo: {
    flex: 1,
  },
  presetName: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
    marginBottom: 4,
  },
  defaultTag: {
    fontSize: 12,
    color: '#888',
  },
  presetTime: {
    fontSize: 14,
    color: '#666',
  },
  presetActions: {
    flexDirection: 'row',
  },
  actionButton: {
    paddingVertical: 6,
    paddingHorizontal: 12,
    borderRadius: 16,
    marginLeft: 8,
  },
  useButton: {
    backgroundColor: '#E3F2FD',
  },
  useButtonText: {
    color: '#2196F3',
    fontWeight: '500',
  },
  deleteButton: {
    backgroundColor: '#FFEBEE',
  },
  deleteButtonText: {
    color: '#F44336',
    fontWeight: '500',
  },
  tipsContainer: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  tipsTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 8,
  },
  tipsText: {
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
  },
});

export default TimerSettingsScreen;